package br.com.guiav6.sisguia.utils;

import java.util.ArrayList;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import br.com.guiav6.sisguia.entity.Especialidade;
import br.com.guiav6.sisguia.entity.TipoServico;
import br.com.guiav6.sisguia.service.TipoServicoService;

@Component("tipoServicoConverter")
@Scope(value = "session")
public class TipoServicoConverter implements Converter{

	@Autowired
	TipoServicoService tipoServicoService;
	
	@Override
	public Object getAsObject(FacesContext fc, UIComponent component, String value) {
		Long id = null;
		if (value != null && !value.isEmpty()){
			try{
				id = Long.parseLong(value);
			}catch (NumberFormatException nfe) {
				TipoServico tipoServico = new TipoServico();
				tipoServico.setNome(value);
				tipoServico.setEspecialidadeList(new ArrayList<Especialidade>());
				return tipoServico;
			}
			return tipoServicoService.findById(id);
		}else{
			return null;
		}
	}

	@Override
	public String getAsString(FacesContext fc, UIComponent component, Object value) {
		if(value != null && value instanceof TipoServico){
			return ((TipoServico) value).getId().toString();
		}
		return "";
	}

}